﻿using System;
using System.Threading.Tasks;
using CzfSDK;

namespace Server
{
	// 
	public class Game
	{
		public static bool DEBUG = true;

		public static bool DEBUG_ROOM = false;
		public static Game current;

		public Game ()
		{
			current = this;
		}

		public void Start()
		{
			// 所有玩家登出
			UserManager.AllUserLogout ();

			// 检测生成NPC
			MConfig.Update();
			UserManager.Login("NPC", "bgdsbhtbs", null);

			// 初始化竞技场
			RoomManager.Init();

			// 判断账号超时
			ThreadTool.TaskRun (()=>{
				while(true){
					try{
						for (int i = 0; i < User.users.Count; i++) {
							var user = User.users[i];
							if(user.client != null && (DateTime.Now - user.last).TotalSeconds > 3000)
							{
								user.Logout();
								i--;
							}
						}
					}catch(Exception e){
						CzfLog.Error("Game.Start", e);
					}
					ThreadTool.TaskDelay(60 * 1000);
				}
			});

			// 更新配置信息
			ThreadTool.TaskRun (()=>{
				while(true){
					try{
//						CzfLog.Info("更新配置文件");
						MConfig.Update();
//						CzfLog.Info("更新配置文件完成");
					}catch(Exception e){
						CzfLog.Error("Game.Start", e);
					}
					ThreadTool.TaskDelay(10 * 1000);
				}
			});

			CzfNetManager.current.OnClientClose += Logout;
		}

		public void Logout(CzfNetManager m, CzfNetClient client){
			var user = User.Get(client);
			if (user != null) {
				user.Logout ();
			}
		}
	}
}

